<template>
  <div>
    <UploadExcel :on-success="upload" />
  </div>
</template>

<script>
import { ImportStaffLists, getStaffLists } from '@/api/staff'
export default {
  components: {

  },
  props: {

  },
  data() {
    return {

    }
  },
  computed: {

  },
  watch: {

  },
  created() {

  },
  mounted() {

  },
  methods: {
    // data.header 就是表头
    // data.results 就是数据
    async upload(data) {
      const user = data.results.map(v => {
        return this.zh2en(v)
      })
      const { rows } = await getStaffLists({ page: 1, size: this.$store.state.user.total })
      // 判断导入的数据是否有重复的工号和和电话号码
      const isRepeat = user.some(user => {
        return rows.some(row => {
          return +row.mobile === +user.mobile || +row.workNumber === +user.workNumber
        })
      })

      if (isRepeat) {
        this.$message.error('手机号或者工号重复')
      } else {
        console.log(user)
        await ImportStaffLists(user)
        this.$message.success('导入成功')
        this.$router.back()
      }
    },
    zh2en(data) {
      const newobj = {}
      const dict = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      for (const key in data) {
        const enkey = dict[key]
        const value = data[key]
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          newobj[enkey] = new Date(this.formatDate(value, '/'))
        } else {
          newobj[enkey] = value
        }
      }
      return newobj
    },
    formatDate(numb, format) { // 转换Exel时间格式
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
    // async adb() {//Promise中return问题 ---在调用的时候加上 async  await
    //   const { rows } = await getStaffLists({ page: 1, size: this.$store.state.user.total })
    //   return rows
    // }

  }
}
</script>

<style scoped lang="less">

</style>
